<?php

declare(strict_types=1);

namespace App\Model\Stat;

use App\Model\UserProfile;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;
use App\Model\User;

/**
 *  每日统计-女用户收入等信息
 */
class StatDailyHostInfo extends Model
{
    protected $connection = 'stat';
    protected $table = 'stat_daily_host_info';
    protected $fillable = ['user_id', 'dt', 'income_total', 'income_gift', 'income_msg', 'income_voice', 'income_video', 'income_sysgift', 'video_answer_time', 'video_answer_num', 'success_rate', 'video_call_num', 'video_match_num', 'msg_back_rate', 'super_chat_num', 'online_time'];

    const SHOW_FIELDS = [
        'online_time' => '平均在线时长（小时）',
        'video_answer_time' => '平均接听时长（分钟）',
        'video_answer_num' => '平均接听次数',
        'success_rate' => '平均接通率',
        'video_call_num' => '平均主动拨打次数',
        'video_match_num' => '平均主动速配次数',
        'msg_back_rate' => '私信回复率',
        'super_chat_num' => '平均主动搭讪人数',
        //名义礼物赠送个数
        'receive_num' => '名义礼物赠送个数',
        //名义礼物赠送人数
        'receive_user_num' => '名义礼物赠送人数',
        //名义礼物回复用户数
        'msg_back_num' => '回复用户数',
    ];

    const RATE_FIELD = ['msg_back_rate', 'success_rate'];

    const CAL_DURATION = [
        '1' => '昨天',
        '4' => '最近3天',
        '16' => '最近15天',
        '31' => '最近30天'
    ];

    /**
     * 平均数
     */
    static function calAverage($start = '', $end = '')
    {
        $where = [
            ['dt', '>=', $start],
            ['dt', '<=', $end],
        ];
        $data = self::where($where)->get()->toArray();
        $result = [];

        foreach ($data as $item) {
            if (!isset($result[$item['user_id']])) {
                self::initAverageField($result[$item['user_id']]);
            }
            foreach (self::SHOW_FIELDS as $field => $desc) {
                $result[$item['user_id']][$field][] = $item[$field];
            }
        }
        foreach ($result as $userId => &$item) {
            foreach (self::SHOW_FIELDS as $field => $desc) {
                $arr = $item[$field];
                if (count($arr) == 0) $item[$field] = 0;
                else $item[$field] = round(array_sum($arr) / count($arr), 1);
            }
        }
        return $result;
    }

    static function initAverageField(&$data = [])
    {
        foreach (self::SHOW_FIELDS as $field => $desc) {
            $data[$field] = [];
        }
    }

    public function userProfile()
    {
        return $this->belongsTo(UserProfile::class, 'user_id', 'user_id');
    }

    /**
     * 按呼叫时长获取主播列表
     */
    static function getCallRankList($num = 30, $start = '', $end = '')
    {
        $where = ["t.dt >= '" .$start."'"];
        $end && $where[] = "t.dt <= '".$end."'";
        $str  = implode(' and ',$where);
        $data = Db::select("select t.user_id , SUM(t.call_minutes) as call_minutes from maoliao_stat.t_stat_daily_host_info  as t left join  t_user as u on u.id = t.user_id where {$str} and u.status = 0 group by t.user_id order by call_minutes desc limit {$num}");
        $ret = [];
        foreach ($data as $k => $v) {
            $ret[] = [
                'user_id' => $v->user_id,
                'call_minutes' => $v->call_minutes,
            ];
        }
        return  $ret;
    }
}
